import {
    CSSProperties, useContext, useMemo, useState,
} from 'react';
import { render, Tab, Tabs } from 'amis';
import {
    Layout, Select, udp, useAsyncEffect, useRefState,
} from '@cscec/udp-ui';
import { observer } from 'mobx-react';
import { Skeleton } from 'antd';
import { asyncForEach, dashToCamel } from '../plugin/base/util';
import { buildRenderers } from '../plugin';
import { RenderersPanel } from './subPanel';
import { DesignContext } from '../context';
import React from 'react';

function LeftTabs({ store, manager, type }: { store: any, manager: any, type: 'portal' | 'lowcode' }) {
    console.log('[debug] store: ',store.groupedSubRenderers, store.groupedCustomRenderers);
    const tabs = useMemo(() => filterRenderers(store.groupedSubRenderers, store.groupedCustomRenderers, type), [store.groupedSubRenderers, store.groupedCustomRenderers]);

    const [activeKey, setActiveKey] = useState(tabs[0].key);

    return (
        <div className="ae-RendererPanel">
            <div className="panel-header">{type === 'portal' ? '容器及组件' : '字段及组件'}</div>
            <div className="ae-RendererPanel-content" style={{ padding: '0 5px' }}>
                <Tabs
                    theme={store.theme}
                    tabsMode="line"
                    className="ae-RendererList-tabs"
                    linksClassName="ae-RendererList-tabs-header"
                    contentClassName="ae-RendererList-tabs-content"
                    activeKey={activeKey}
                    onSelect={setActiveKey}
                >
                    {
                        tabs.map((tab) => (
                            <Tab
                                key={tab.key}
                                eventKey={tab.key}
                                title={tab.title}
                                className="ae-RendererList-tabs-panel base-renderers"
                                mountOnEnter
                                unmountOnExit={false}
                            >
                                {tab.key === 'remote' ? (
                                    <Remote
                                        store={store}
                                        manager={manager}
                                    />
                                ) : (
                                    <RenderersPanel
                                        groupedRenderers={tab.renderers}
                                        store={store}
                                        manager={manager}
                                    />
                                )}
                            </Tab>
                        ))
                    }
                </Tabs>
            </div>
        </div>
    );
}
export default observer(LeftTabs);

// 组件市场
function Remote({ store, manager }: any) {
    const [state, setState] = useRefState({ packages: [], currentId: '', loading: false });

    const ctx = useContext(DesignContext);

    useAsyncEffect(async () => {
        if (ctx.store?.packages) {
            return;
        }
        setState({ loading: true });
        try {
            const { code, data } = await udp.request.get({
                url: `/udp-market/market/low-code/package/versions?moduleCode=${udp.getQueryValue('appCode')}`,
            });
            if (code === 0 && data?.length) {
                const packages = data.map((pkg: { id: string; pkgName: string; pkgVer: string }) => ({ value: pkg.id, label: `${pkg.pkgName}@${pkg.pkgVer}` }));
                setState({ packages, currentId: packages[0].value });
            } else {
                setState({ loading: false });
            }
        } catch (e) {
            console.log(e);
        }
    }, []);

    useAsyncEffect(async () => {
        if (!state.currentId) {
            return;
        }

        const resource: any = {};
        try {
            setState({ loading: true });
            const { code, data: list } = await udp.request.get({
                url: `/udp-market/market/low-code/package/components/${state.currentId}`,
            });
            if (code === 0) {
                await asyncForEach(list, async ({ integrateResources, cptName, cptVer }: any) => {
                    integrateResources?.forEach(({ resUrl, resCptName }: any) => {
                        const url = resUrl || '';
                        if (url?.endsWith('.js')) {
                            const key = resCptName || dashToCamel(url.split('/').pop().split('.')[0]);
                            resource[key] = {
                                url, name: resCptName, title: cptName, ver: cptVer, pid: state.currentId,
                            };
                        }
                    });
                });
            }
        } catch (e) {
            console.log(e);
        }
        await buildRenderers(resource, manager);
        ctx.setStore({ packages: resource });
        setState({ loading: false });
    }, [state.currentId]);

    const renderers = useMemo(() => filterRenderers({}, store.groupedCustomRenderers, 'remote')[0].renderers, [store.groupedCustomRenderers]);

    const onPackageChange = (id: any) => {
        setState({ currentId: id });
    };

    if (state.loading) {
        return <Skeleton active />;
    }

    return (
        <Layout>
            {state.currentId ? <Select options={state.packages} labelInValue={false} value={state.currentId} onChange={onPackageChange} style={{ marginRight: 12 }} /> : null}
            <Layout.Flex>
                <RenderersPanel
                    groupedRenderers={renderers}
                    store={store}
                    manager={manager}
                />
            </Layout.Flex>
        </Layout>
    );
}

function filterRenderers(system: Record<string, any[]>, custom: Record<string, any[]>, formType: 'portal' | 'lowcode' | 'remote') {
    const tabs: any[] = [];
    const counts = { field: 0, sys: 0, remote: 0, customTable: 0};
    const fieldRenders: Record<string, { style?: CSSProperties, items: any[], total: number }> = {};
    const sysRenderers: Record<string, { style?: CSSProperties, items: any[], total: number }> = {};
    const remoteRenderers: Record<string, { style?: CSSProperties, items: any[], total: number }> = {};
    const customTableRenders: Record<string, { style?: CSSProperties, items: any[], total: number }> = {};
    const renderers = system || {};
    const customRenders = custom || {};
    let inKeyCount = 0;
    Object.keys(renderers).forEach(key => {
        renderers[key].forEach(renderer => {
            if (renderer.disabledRendererPlugin) {
                return;
            }
            if ((formType === 'lowcode' && renderer.type) || (formType === 'portal' && ['flex', 'grid', 'container', 'udp-tpl', 'link', 'iframe'].includes(renderer.rendererName))) {
                sysRenderers[key] = sysRenderers[key] || { items: [], total: 0 };
                sysRenderers[key].items.push(renderer);
                sysRenderers[key].total++;
                counts.sys++;
            } else if (formType === 'lowcode' && ['table', 'form'].includes(renderer.rendererName)) {
                const inKey = '常用组件';
                inKeyCount++;
                renderer.order = -9000 + inKeyCount;
                sysRenderers[inKey] = sysRenderers[inKey] || { items: [], total: 0 };
                sysRenderers[inKey].items.push(renderer);
                sysRenderers[inKey].total++;
                counts.sys++;
            }
        });
    });

    Object.keys(customRenders).forEach((key) => {
        customRenders[key].forEach((renderer) => {
            if (renderer.disabledRendererPlugin) {
                return;
            }

            if (formType === 'lowcode') {
                if(renderer.type === 'data-plugin'){
                    fieldRenders[key] = fieldRenders[key] || { style: { margin: '0 17px 12px 10px', width: '100%', flex: 'auto' }, items: [], total: 0 };
                    fieldRenders[key].items.push(renderer);
                    fieldRenders[key].total++;
                    counts.field++;
                }else if(renderer.type === 'specified-table-plugin'){
                    customTableRenders[key] = customTableRenders[key] || { style: { margin: '0 17px 12px 10px', width: '100%', flex: 'auto' }, items: [], total: 0 };
                    customTableRenders[key].items.push(renderer);
                    customTableRenders[key].total++;
                    counts.customTable++;
                }
                
            }
            if (formType === 'portal' && (renderer.type === 'portal')) {
                sysRenderers[key] = sysRenderers[key] || { style: { margin: '0 17px 12px 10px', width: '100%', flex: 'auto' }, items: [], total: 0 };
                sysRenderers[key].items.push(renderer);
                sysRenderers[key].total++;
                counts.sys++;
            }
            //组件市场先不考虑
            if (renderer.type === 'remote') {
                remoteRenderers[key] = remoteRenderers[key] || { style: { margin: '0 17px 12px 10px', width: '100%', flex: 'auto' }, items: [], total: 0 };
                remoteRenderers[key].items.push(renderer);
                remoteRenderers[key].total++;
                counts.remote++;
            }
        });
    });
    if (formType === 'remote') {
        // tabs.push({
        //     title: '组件市场', key: 'remote', renderers: remoteRenderers, total: counts.remote,
        // });
    } else {
        counts.customTable && tabs.push({
            title: '自定义表格', key: 'customTable', renderers: customTableRenders, total: counts.customTable,
        });
        counts.field && tabs.push({
            title: '字段', key: 'field', renderers: fieldRenders, total: counts.field,
        });
        counts.sys && tabs.push({
            title: '系统', key: 'system', renderers: sysRenderers, total: counts.sys,
        });
        // tabs.push({
        //     title: '组件市场', key: 'remote', renderers: remoteRenderers, total: counts.remote,
        // });
    }
    return tabs;
}
